//
//  SEHospitalDetailController.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/4/6.
//

import UIKit

class SEHospitalDetailViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = true
            tableView.separatorColor = UIColor.init(hex: "EBECF0")
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            tableView.tableFooterView = UIView()
            tableView.register(UINib(nibName: SEHospitalDetailInfoCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalDetailInfoCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalDetailServiceCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalDetailServiceCell.reuseId)
            tableView.register(UINib(nibName: SEHospitalDetailDoctorCell.className, bundle: nil), forCellReuseIdentifier: SEHospitalDetailDoctorCell.reuseId)
        }
    }

    var viewModel = SEHospitalDetailViewModel()

    init(with hospitalId: String) {
        viewModel.model.id = hospitalId
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        title = "医院详情"
        requestHospitalDetail()
        // Do any additional setup after loading the view.
    }

    @objc private func rightItemAction() {
        requestFollowedHospital()
    }

    override func setupUI() {
        super.setupUI()
        viewModel.updateData = { status in
            switch status {
            case .success:
                self.tableView.isHidden = false
                self.tableView.reloadData()
                self.updateRightItem()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestHospitalDetail)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }

        viewModel.followedHandler = { status in
            switch status {
            case .success:
                self.viewModel.model.status = self.viewModel.model.status == 1 ? 2 : 1
                self.updateRightItem()
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.requestFollowedHospital)) {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    private func updateRightItem() {
        let btn = UIButton(type: .custom)
        btn.widthAnchor.constraint(equalToConstant: 50).isActive = true
        btn.heightAnchor.constraint(equalToConstant: 24).isActive = true
        btn.layer.cornerRadius = 12
        btn.layer.masksToBounds = true
        btn.backgroundColor = Asset.main.color
        let title = viewModel.model.status == 1 ? "已关注" : "关注"
        btn.setTitle(title, for: .normal)
        btn.titleLabel?.font = UIFont.regular(13)
        btn.addTarget(self, action: #selector(rightItemAction), for: .touchUpInside)
        let rightItem = UIBarButtonItem(customView: btn)
        navigationItem.rightBarButtonItem = rightItem
    }
    

}

// MARK: - UITableViewDataSource,UITableViewDelegate

extension SEHospitalDetailViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalDetailInfoCell.reuseId, for: indexPath) as! SEHospitalDetailInfoCell
            cell.updateData(viewModel)
            cell.delegate = self
            return cell
        }

        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalDetailServiceCell.reuseId, for: indexPath) as! SEHospitalDetailServiceCell
            cell.delegate = self
            cell.updateCell(viewModel)
            return cell
        }

        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEHospitalDetailDoctorCell.reuseId, for: indexPath) as! SEHospitalDetailDoctorCell
            cell.delegate = self
            cell.updateData(viewModel.doctorModel(indexPath: indexPath))
            return cell
        }

        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows(section: section)
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 1: return 90
        case 2: return 82
        default: return UITableView.automaticDimension
        }
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2 {
            return 46
        }
        return 0
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = SEHospitalDetailSectionHeader()
        return view
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        return view
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 2 else { return }
        let model = viewModel.doctorModel(indexPath: indexPath)
        pushToDoctorDetail(model)
    }
}

// MARK: - SEHospitalDetailInfoCellDelegate

extension SEHospitalDetailViewController: SEHospitalDetailInfoCellDelegate {
    func hospitalDetailInfoCellZoomBtnAction(cell: SEHospitalDetailInfoCell) {
        tableView.reloadData()
    }
}

// MARK: - SEHospitalDetailServiceCellDelegate

extension SEHospitalDetailViewController: SEHospitalDetailServiceCellDelegate {
    func hospitalDetailServiceCellAction(_ actionType: SEHospitalDetailServiceCellActionType) {
        switch actionType {
        case .registration:
            pushToRegistrationDept()
        case .advisory:
            pushToDoctorList()
        case .check:
            pushToExamineReserve()
        }
    }

    private func pushToRegistrationDept() {
        let vc = SERegistrationTypeController(with: viewModel.hospitalListItem)
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToDoctorList() {
        let vc = SEDoctorListViewController(fromType: .hospitalize, departmentId: "", hospitalId: viewModel.model.id)
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToExamineReserve() {
        let vc = SEExamineReserveViewController(with: viewModel.hospitalListItem, checkSource: 1)
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToDoctorDetail(_ model: SEDoctorDetail) {
        let vc = SEDoctorDetailViewController(with: model.id ?? "")
        navigationController?.pushViewController(vc, animated: true)
    }

    private func pushToOnlineReserve(_ model: SEDoctorDetail) {
        let vc = SEOnlineReserveViewController(doctorDetailVM: SEDoctorDetailViewModel(model: model))
        vc.title = "就诊信息填写"
        navigationController?.pushViewController(vc, animated: true)
    }

}

extension SEHospitalDetailViewController: SEHospitalDetailDoctorCellDelegate {
    func hospitalDetailDoctorCellBtnAction(model: SEDoctorDetail) {
        pushToOnlineReserve(model)
    }
}

// MARK: - APIRequest

extension SEHospitalDetailViewController {
    @objc func requestHospitalDetail() {
        viewModel.requestHospitalDetail()
    }

    @objc func requestFollowedHospital() {
        viewModel.requestFollowedHospital()
    }
}
